#include "push_predis.h"

extern void push_db_data(string addr, string query, string error, long execute_micro_time);

void push_predis_handler(zend_execute_data *execute_data, long execute_micro_time, string class_name, string function_name)
{
    php_printf("push_predis_handler\n");

    // 初始化参数
    string operate = "";
    string key = "";
    string ip = "";
    string port = "";
    string addr = "";
    string err = "";
    string query = "";

    zval *connection = read_property(execute_data->object, "connection");
    if (connection == nullptr)
    {
        return;
    }
    zval *parameters = read_property(connection, "parameters");
    if (parameters == nullptr)
    {
        return;
    }
    zval *params = read_property(parameters, "parameters");
    if (params == nullptr)
    {
        return;
    }

    // print_hashtable_zval(params);

    zval **z_host;
    if (SUCCESS == zend_hash_find(HASH_OF(params), "host", sizeof("host"), (void **)&z_host))
    {
        ip = Z_STRVAL_PP(z_host);
    }
    zval **z_port;
    if (SUCCESS == zend_hash_find(HASH_OF(params), "port", sizeof("port"), (void **)&z_port))
    {
        port = to_string(Z_LVAL_PP(z_port));
    }
    addr = ip + ":" + port;

    zval *id = func_get_arg(execute_data, 1);
    if (id != nullptr && Z_TYPE_P(id) == IS_STRING)
    {
        operate = Z_STRVAL_P(id);
    }

    query = class_name + "->" + function_name + "::" + operate;

    push_db_data(addr, query, err, execute_micro_time);
}